<template>
  <div class="ele-body">
    <el-card shadow="never" style="min-height: 50px;position: relative">
      <div class="right-handle-group" style="cursor: pointer">
        <a style="margin-left: 8px" @click="toggleAdvanced">
          {{ advanced ? '收起' : '展开' }}
          <i :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" />
        </a>
      </div>
      <el-collapse-transition >
      <div class="searchWrap" v-show="advanced">
        <div class="searchBox"><span>状态视角:</span>
          <div @click="selectAll('statusActiveNum')"
               class="searchItem"
               :class="statusActiveNum==='' ? 'active':''">全部({{ allStatusNum ? allStatusNum : 0 }})
          </div>
          <div @click="searchByStatusVersion(item,index)" class="searchItem"
               :class="statusActiveNum === index||(item==='已开始'&&$route.query.status&&where.status==='process') ? 'active':''"
               v-for="(item,index) in workTicketStatusList" :key="item">{{ item }} ({{ statusNumList[item] || 0 }})
          </div>
        </div>
        <div class="searchBox"><span>创建视角：</span>
          <div @click="selectAll('createActiveNum')"
               class="searchItem"
               :class="createActiveNum==='' ? 'active':''">全部
          </div>
          <div @click="searchByCreate(item.code,index)" class="searchItem"
               :class="createActiveNum === index ? 'active':''" v-for="(item,index) in workTicketCreateList"
               :key="item.code">{{ item.text }}
          </div>
        </div>
        <div class="searchBox"><span>工单类型：</span>
          <div @click="selectAll('activeNum')"
               class="searchItem"
               :class="activeNum==='' ? 'active':''">全部
          </div>
          <div @click="searchByType(item,index)" class="searchItem"
               :class="activeNum === index ? 'active':''" v-for="(item,index) in workTicketTypeList"
               :key="item">{{ item }}
          </div>
        </div>
        <div class="searchBox"><span>时间范围：</span>
          <div @click="selectAll('dateActiveNum')"
               class="searchItem"
               :class="dateActiveNum==='' ? 'active':''">全部
          </div>
          <div @click="searchByDate(item,index)" class="searchItem"
               :class="dateActiveNum === index ? 'active':''" v-for="(item,index) in dateList"
               :key="index">{{ Object.keys(item)[0] }}
          </div>
        </div>
      </div>
      </el-collapse-transition>
    </el-card>
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form :model="where" class="ele-form-search" label-width="77px" @keyup.enter.native="reload"
               @submit.native.prevent>
        <el-row :gutter="15">
          <el-col :lg="6" :md="12">
            <el-form-item label="工单信息:">
              <el-input v-model="where.number" clearable placeholder="请输入工单编号"/>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="负责人:">
            <el-select
              v-model="where.user_id"
              filterable
              remote
              @focus="remoteMethod('')"
              placeholder="请搜索项目负责人"
              :remote-method="remoteMethod"
              :loading="loading"
              style="width: 100%"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :value="item.id"
                :label="item.realname">
                <div><b>{{ item.realname }}</b> &nbsp; &nbsp;&nbsp;部门: <span>{{ item.dept_name }}</span> &nbsp;&nbsp;&nbsp;&nbsp;岗位:
                  <span>{{ item.position_name }}</span></div>
              </el-option>
            </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="6" :md="12">
            <el-form-item label="日期范围:">
              <el-date-picker
                style="width: 100%;"
                v-model="date"
                type="monthrange"
                value-format="yyyy-MM"
                range-separator="至"
                start-placeholder="开始月份"
                end-placeholder="结束月份">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <div class="ele-form-actions">
              <el-button v-if="permission.includes('sys:workTickets:index')" class="ele-btn-icon" icon="el-icon-search"
                         type="primary" @click="reload">
                查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 数据表格 -->
      <ele-pro-table ref="table" :columns="columns" :datasource="url" :selection.sync="selection" :where="where"
                     :height="advanced?'calc(100vh - 505px)':'calc(100vh - 355px)'">
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <div class="btnWrap">
            <el-dropdown @command="handleCommand">
              <el-button icon="el-icon-plus" size="small" type="primary"
                         v-show="permission.includes('sys:workTickets:add')">
                添加
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="item in typeList" :key="item" :command="item">{{ item }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="btnWrap" v-if="permission.includes('sys:workTickets:export')">

            <download-excel
              class="export-excel-wrapper"
              :data="selection"
              :fields="json_fields"
              :header="title"
              name="工单.xls"
              :before-generate="startDownload"
              :before-finish="finishDownload"
            >
              <el-button size="small" type="primary" :loading="exportFlag" :disabled="!selection.length&&!exportFlag">
                导出
              </el-button>
            </download-excel>

          </div>
          <div class="btnWrap">
            <el-button size="small" :loading="exportLoading" type="primary"
                       v-if="permission.includes('sys:workTickets:export')" @click="exportAll">导出全部
            </el-button>
          </div>
        </template>
        <!--工单编号-->
        <template slot="wo_number" slot-scope="{row}">
          <span style="cursor: pointer;color: var(--color-primary)"
                @click="$router.push('/workTickets/workTickets/info?id=' + row.id)">
            {{ row.wo_number }}
          </span>
        </template>

        <!--创建方式-->
        <template slot="createType">
          <span>客服创建</span>
        </template>
        <!--派单人-->
        <template slot="dispatch" slot-scope="{row}">
          <span>{{ row.logs.length >= 2 ? row.logs[1].creator : '' }}</span>
        </template>
        <!--产品-->
        <template slot="products" slot-scope="{row}">
          {{ formProducts(row) }}
        </template>
        <!--地址-->
        <template slot="address" slot-scope="{row}">
          <span>{{ row.province_name }} {{ row.city_name }} {{ row.county_name }} {{ row.address }}</span>
        </template>
        <!--负责人-->
        <template slot="master" slot-scope="{row}">
          <span>{{ formMaster(row) }}</span>
        </template>
        <!--协调人-->
        <template slot="synergistic_people" slot-scope="{row}">
          <span>{{ formSynergistic_people(row) }}</span>
        </template>
      </ele-pro-table>
    </el-card>
  </div>
</template>

<script>
import {mapGetters} from "vuex";


export default {
  computed: {
    ...mapGetters(["permission"])
  },
  data() {
    return {
      advanced:true,
      options:[],
      exportFlag: false,
      exportLoading: false,
      title: "嘉盛环境工单表格",
      json_fields: {
        "工单编号": 'wo_number',
        "工单类型": 'type',
        "客户": 'customer.name',

        "联系人": {
          field: "contact_name",
          //自定义回调函数
          callback: value => {
            return value + ' '
          }
        },
        "电话": 'contact_phone',
        "客户地址": 'customer.detail_address',
        "出厂编号": {
          field: "products",
          //自定义回调函数
          callback: value => {
            return `${(value.map(item => {
              return item.product?.name
            })).join(',')}`;
          }
        },
        "产品编号": {
          field: "products",
          //自定义回调函数
          callback: value => {
            return `${(value.map(item => {
              return item.product?.product_number
            })).join(', ')}`;
          }
        },
        "质保开始时间": {
          field: "products",
          //自定义回调函数
          callback: value => {
            return `${(value.map(item => {
              return item.product?.warranty_start_date
            })).join(',')}`;
          }
        },
        "质保结束时间": {
          field: "products",
          //自定义回调函数
          callback: value => {
            return `${(value.map(item => {
              return item.product?.warranty_end_date
            })).join(',')}`;
          }
        },
        "质保状态": {
          field: "products",
          //自定义回调函数
          callback: value => {
            return `${(value.map(item => {
              return item.product?.warranty_status_title
            })).join(',')}`;
          }
        },
        "优先级": 'level',
        "服务类型": 'service_type',
        "服务内容": 'service_content',
        "计划时间": 'plan_at',

        "备件名称": 'remark',
        "备件编号": 'remark',
        "备件类别": 'remark',
        "备件规格": 'remark',
        "备件数量": 'remark',
        "备件价格": 'remark',
        "服务项目": 'remark',
        "服务类别": 'remark',
        "服务项目数量": 'remark',
        "服务项目金额": 'remark',
        "工单总价": 'remark',
        "折扣费用": 'remark',
        "工单合计": 'remark',
        "工单状态": 'status',
        "创建人": 'create_user.realname',
        "派单人": {
          field: "logs",
          //自定义回调函数
          callback: value => {
            if (value[1]) {
              return value[1].creator
            }
          }
        },
        "负责人": {
          field: "users",
          //自定义回调函数
          callback: value => {
            return `${(value.filter(item => {
              return item.is_master === 1
            }))[0].user.realname}`;
          }
        },
        "审核人": {
          field: "audit_show",
          //自定义回调函数
          callback: value => {
            return `${(value.map(item => {
              return item.auditor
            })).join(',')}`;
          }
        },
        "服务网点": 'customer.department_name',
        "协同人": {
          field: "users",
          //自定义回调函数
          callback: value => {
            return `${(value.filter(item => {
              return item.is_master === 0
            })).map(item => {
              return item.user.realname
            }).join(',')}`;
          }
        },
        "创建时间": 'create_time_format',
        "派单时间": {
          field: "logs",
          //自定义回调函数
          callback: value => {
            if (value[1]) {
              return value[1].create_time
            }
          }
        },
        "接受时间": {
          field: "logs",
          //自定义回调函数
          callback: value => {
            if (value[2]) {
              return value[2].create_time
            }
          }
        },
        "开始时间": {
          field: "logs",
          //自定义回调函数
          callback: value => {
            if (value[3]) {
              return value[3].create_time
            }
          }
        },

        "转派时间": 'remark',

        "完成时间": {
          field: "logs",
          //自定义回调函数
          callback: value => {
            if (value[4]) {
              return value[4].create_time
            }
          }
        },
        "审核状态": {
          field: "audit_show",
          //自定义回调函数
          callback: value => {
            if (value.length === 0) {
              return '未审核'
            } else if (value.length === 1) {
              return '一级'
            } else if (value.length === 2) {
              return '二级'
            }
          }
        },
        "回访时间": 'callback_show[0].time',
      },
      typeList: [],
      // 表格数据接口
      url: '/wos',
      // 表格列配置
      columns: [
        {
          columnKey: 'selection',
          type: 'selection',
          width: 45,
          align: 'center',
          fixed: "left"
        },
        {
          slot: 'wo_number',
          label: '工单编号',
          width: 150,
          align: 'center',
          showOverflowTooltip: true,
        },
        {
          prop: 'type',
          label: '工单类型',
          showOverflowTooltip: true,
          minWidth: 120,
          align: 'center',
        },
        {
          prop: 'customer.name',
          label: '客户',
          showOverflowTooltip: true,
          minWidth: 150,
          align: 'center'
        },
        {
          prop: 'contact_name',
          label: '联系人',
          align: 'center',
          showOverflowTooltip: true,
          width: 100
        },

        {
          prop: 'contact_phone',
          label: '电话',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center'
        },
        {
          slot: 'address',
          label: '客户地址',
          showOverflowTooltip: true,
          minWidth: 250,
          align: 'center'
        },
        {
          slot: "products",
          label: '产品',
          showOverflowTooltip: true,
          minWidth: 150,
          align: 'center'
        },
        {
          prop: 'plan_at',
          label: '计划时间',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center'
        },
        {
          slot: 'master',
          label: '负责人',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          slot: 'synergistic_people',
          label: '协同人',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center'
        },
        {
          prop: 'status',
          label: '工单状态',
          minWidth: 160,
          align: 'center',
        },
        {
          prop: 'create_user.nickname',
          label: '创建人',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center',
        },
        {
          prop: 'create_time_format',
          label: '创建时间',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center',
        },
        {
          slot: 'dispatch',
          label: '派单人',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center',
        },
        {
          slot: 'createType',
          label: '创建方式',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center',

        },
        // {
        //   columnKey: 'action',
        //   label: '操作',
        //   width: 150,
        //   align: 'center',
        //   resizable: false,
        //   slot: 'action',
        //   fixed: "right"
        // }
      ],
      loading: false,
      //显示新增联系人
      showCustomerUserEdit: false,
      //显示编辑选项
      isEditType: false,
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      //当前编辑的类型
      type: '',
      // 当前编辑数据
      current: '',
      // 是否显示编辑弹窗
      showEdit: false,
      // 二维码是否显示编辑弹窗
      codeEdit: false,
      // 当前编辑数据
      currentCode: '',
      // 是否显示导入弹窗
      showImport: false,
      //客户id
      customer_id: '',
      //客户名字
      customer_name: '',
      //工单类型筛选
      workTicketTypeList: [],
      //工单状态筛选
      workTicketStatusList: [],
      //创建人筛选
      workTicketCreateList: [],
      //状态搜索激活
      activeNum: '',
      //类型搜索激活
      statusActiveNum: '',
      //创建人搜索激活
      createActiveNum: '',
      //工单各个数量
      statusNumList: {},
      //全部工单数量
      allStatusNum: 0,
      //时间范围筛选
      dateActiveNum: '',
      dateList: [
        {今天: 'today'},
        {本周: 'week'},
        {本月: 'month'},
        {本年: 'year'}
      ],
      date:[],
    };
  },
  watch: {},
  mounted() {
    this.$http.get(`wos/params`,).then((res) => {
      this.workTicketStatusList = res.data.data.status
      this.workTicketTypeList = res.data.data.wo_types
      this.typeList = res.data.data.wo_types
      this.workTicketCreateList = res.data.data.about_me
      return res.data.data.status
    }).then((res) => {
      if (this.$route.query.status) {
        this.statusActiveNum = res.findIndex((item) => item === this.$route.query.status)
        this.where.status = this.$route.query.status
        this.reload()
      }
    })
    this.getStatusNum()
  },
  beforeMount() {
    let storageWoStatus = localStorage.getItem('wo_status') ?? '';
    if (storageWoStatus !== '') {
      if (storageWoStatus === 'un_complete') {
        this.statusActiveNum = 5
      } else if (storageWoStatus === 'exception') {
        this.statusActiveNum = 8
      } else if (storageWoStatus === 'processing') {
        this.statusActiveNum = 6
      }
      this.url = '/wos?status=' + storageWoStatus
    } else {
      this.url = '/wos';
    }
    localStorage.removeItem('wo_status');
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    remoteMethod(query = '') {
      this.loading = true
      this.$http.get(`/user/index?limit=10&realname=${query} `).then((res) => {
        if (res.data.code == 0) {
          this.options = res.data.data.filter(item => {
            return item.id !== 1
          })
          this.options1 = res.data.data.filter(item => {
            return item.id !== 1
          })
          this.loading = false
        }
      });
    },
    startDownload() {
      if (this.selection.length === 0)
        return false
      this.exportFlag = true
    },
    finishDownload() {
      this.exportFlag = false
    },
    /*导出全部*/
    exportAll() {
      this.exportLoading = true
      this.$http.get(`wos?export=1`,{params:this.where}).then((res) => {
        this.exportLoading = false
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          const link = document.createElement('a')
          //_blank表示在新窗口打开链接
          // link.target = '_blank'
          link.href = res.data.data
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    //获取工单各个状态数量
    getStatusNum() {
      this.$http.get(`wos/status_counts`,).then((res) => {
        this.statusNumList = res.data.data
          this.allStatusNum = this.statusNumList.总服务
      });
    },
    //筛选全部
    selectAll(flag) {
      switch (flag) {
        case 'activeNum':
          this.activeNum = ''
          this.where.type = ''
          break;
        case 'statusActiveNum':
          this.statusActiveNum = ''
          this.where.status = ''
          break;
        case 'createActiveNum':
          this.createActiveNum = ''
          this.where.about_me = ''
          break;
        case 'dateActiveNum':
          this.dateActiveNum = ''
          this.where.date = ''
          break;
      }
      this.reload()
    },
    //根据时间筛选
    searchByDate(item, index) {
      this.dateActiveNum = index
      let date = item[(Object.keys(item)[0])]
      this.handelDateSearch(date)
    },
    handelDateSearch(date) {
      this.where.date = date
      this.reload()
    },
    //根据创建人搜索
    searchByCreate(code, index) {
      this.createActiveNum = index
      this.handelCreateSearch(code)
    },
    //根据工单状态视角搜索
    searchByStatusVersion(item, index) {
      this.statusActiveNum = index
      this.handelStatusSearch(item)
    },
    //根据工单类型搜索
    searchByType(item, index) {
      this.activeNum = index
      this.handelTypeSearch(item)
    },

    //创建人搜索
    handelCreateSearch(code) {
      this.where.about_me = code
      this.reload()
    },
    //状态搜索请求
    handelStatusSearch(item) {
      let status = ''
      switch (item) {
        case "已创建":
          status = "un_assign"
          break;
        case "已指派":
          status = "assigned"
          break;
        case "已接受":
          status = "accept"
          break;
        case "已开始":
          status = "process"
          break;
        case "已完成":
          status = "complete"
          break;
        case "未完成":
          status = 'un_complete'
          break;
        case '进行中':
          status = 'processing'
          break;
        case "已关闭":
          status = "closed"
          break;
        case "异常工单":
          status = "exception"
          break;
      }
      this.where.status = status
      this.reload()
    },
    //工单类型搜索
    handelTypeSearch(item) {
      this.where.type = item
      this.reload()
    },

    //数据处理
    formProducts(row) {
      return (row.products.map(item => {
        return item?.product?.name
      })).join(' ')
    },
    formMaster(row) {
      if (row.users.filter((item) => {
        return item.is_master === 1
      })) {
        if (((row.users.filter((item) => {
          return item.is_master === 1
        }))[0])) {
          return (((row.users.filter((item) => {
            return item.is_master === 1
          }))[0]).user).realname
        }
      }
    },
    formSynergistic_people(row) {
      return ((row.users.filter((item) => {
        return item.is_master === 0
      })).map(item => {
        return item.user.realname
      })).join(' ')
    },
    handleCommand(command) {
      this.$router.push({path: '/workTickets/workTickets/addWorkTicket', query: {type: command}})
    },
    /* 刷新表格 */
    reload() {
      this.url = '/wos';
      if (this.date?.length >= 0) {
        this.where.date_start = this.date[0]
        this.where.date_end = this.date[1]
      }
      this.$refs.table.reload({where: this.where});
      this.getStatusNum()

    },
    /* 重置搜索 */
    reset() {
      this.activeNum = ''
      this.statusActiveNum = ''
      this.createActiveNum = ''
      this.dateActiveNum = ''
      this.type = ''
      this.isEditType = false;
      this.where = {};
      this.date = []
      this.reload();
    },
  }
}
</script>

<style scoped lang="scss">
.tableTop {
  display: flex;
  justify-content: space-between;
}

.searchWrap {
}

.active {
  background: #dcf3fd;
  border-color: #d0f3f4;
  color: #02aef3 !important;
  padding: 4px 8px;
}

.searchBox {
  display: flex;

  span {
    color: #a7b5b5;
    display: block;
    width: 110px;
    height: 36px;
    font-size: 16px;
  }

  .searchItem {
    border: 1px solid transparent;
    border-radius: 4px;
    color: gray;
    font-size: 13px;
    margin: 0 12px 8px 0;
    max-width: 160px;
    overflow: hidden;
    padding: 4px 8px;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
    font-size: 14px;
  }
}

.el-autocomplete {
  width: 100%;

}

.el-input {
  width: 100% !important;
}

.btnWrap {
  display: flex;

  .el-button {
    margin-right: 10px;
  }
}
.right-handle-group{
  position: absolute;
  right: 50px;
}
</style>
